import React from 'react';
import ReactDOM from 'react-dom';
import Router from 'next/router';
import LazyLoad from 'react-lazyload';
import { Grid, ListView, Icon, NavBar } from 'antd-mobile';

import HeadC from '../src/components/layout/head';
import CustomSearchBar from '../src/containers/customSearchBar';
import CustomCarousel from '../src/containers/customCarousel';
import SingleItem from '../src/components/singleItem';

import { postRequest, getRequest } from '../tools/requests';

import './index.css';

const NUM_ROWS = 10;
let pageIndex = 1;

function genData(pIndex = 1) {
  const dataBlob = {};
  for (let i = 0; i < NUM_ROWS; i++) {
    const ii = (pIndex * NUM_ROWS) + i;
    dataBlob[`${ii}`] = `row - ${ii}`;
  }
  return dataBlob;
}


function MyListViewBody(props, gridData) {
  return (
    <div className="am-list-body">
			<Grid 
				data={props.gridData} 
				columnNum={5}
				hasLine={false}
				itemStyle={{ paddingBottom: '.15625rem' }}
				renderItem={dataItem => (
					<div className="grid-block" onClick={() => Router.push({pathname: '/categories', query: {cateName: dataItem.name, cateId: dataItem.id}})}>
						<LazyLoad>
							<img src={dataItem.category_ico} alt="" />
						</LazyLoad>
						<div>
							<span>{dataItem.name}</span>
						</div>
					</div>
				)}
			/>
      { props.children }
    </div>
  );
}

export default class HomePage extends React.Component {
	static async getInitialProps() {
		let goodsLists, firstCategories, carouselData;
		pageIndex = 1;
		const fetchGoodsLists = await getRequest('goods_list/', {page: pageIndex, page_size: 10})
		goodsLists = fetchGoodsLists.data ? fetchGoodsLists['data'] : [];
    const fetchCategory = await getRequest('get_primary_classify/')
    if (fetchCategory) firstCategories = fetchCategory; 

    // const fetchCarouseData = await getRequest('get_home_carousel/')
    // if (fetchCarouseData) carouselData = fetchCarouseData
		return {
			title: 'coupon',
			description: '',
			links: '',
			ogImage: '',
			goodsLists: goodsLists,
			gridData: firstCategories,
			// carouselData: carouselData
		}
	}
	constructor(props) {
		super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    this.state = {
    	goodsLists: [],
      dataSource,
      isLoading: true,
			height: 0,
			appHeight: 0,
    };
	}
	componentDidMount() {
		// document.body.setAttribute('ontouchstart', '')
		// const docHeight = document.documentElement.clientHeight;
		// const hei = docHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop;
		// this.setState({
		// 	appHeight: docHeight,
		// })
    this.rData = genData();
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(this.rData),
      isLoading: false,
      goodsLists: this.props.goodsLists,
      // height: hei,
    });
	}

 	async onEndReached(event) {
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }
    this.setState({ isLoading: true });
		let pageAdd = ++pageIndex;
    const result = await getRequest('goods_list/', {page: pageAdd, page_size: 10});
    if (result['data']) {
    	this.rData = { ...this.rData, ...genData(pageAdd) };
    	this.setState({
    		goodsLists: result.data,
	      dataSource: this.state.dataSource.cloneWithRows(this.rData),
	      isLoading: false,
	    });
    }
  }

	render() {
		const { title, description, links, ogImage } = this.props;
		let index = this.state.goodsLists.length - 1;
    const row = (rowData, sectionID, rowID) => {
      if (index < 0) {
        index = this.state.goodsLists.length - 1;
      }
			const objImg = this.state.goodsLists[index--];
      return (
				<SingleItem key={rowID} item={objImg}></SingleItem>
      );
    };
		return (
			<div className="app-block">
				{/* html 头部信息 */}
				<HeadC 
					title={title} 
					description={description}
					links={links}
					ogImage={ogImage}
				></HeadC>

				{/* 搜索框 */}
				{/* <CustomSearchBar isHomePage={true} /> */}

				{/* 轮播图 */}
				{/* <div className="carousel-block"> */}
					{/* <CustomCarousel carouselData={this.props.carouselData} /> */}
					{/* <img src="../static/images/coupon.jpg" /> */}
				{/* </div> */}

				{/* 头部 */}
				<NavBar
          mode="light"
          style={{color: '#fa4d47'}}
          className="detail-nav-block"
        >
          首页
        </NavBar>

				{/* 列表 */}
				<ListView
          ref={el => this.lv = el}
          dataSource={this.state.dataSource}
          renderFooter={() => (<div style={{ padding: '15px', textAlign: 'center' }}>
            {this.state.isLoading ? <Icon type="loading" /> : ''}
          </div>)}
          renderRow={row}
          renderBodyComponent={() => <MyListViewBody gridData={this.props.gridData} />}
          className="am-list"
          pageSize={10}
          useBodyScroll
          onScroll={() => { console.log('scroll'); }}
          scrollRenderAheadDistance={500}
          onEndReached={this.onEndReached.bind(this)}
          onEndReachedThreshold={10}
          style={{marginTop: '46px'}}
        />
			</div>
		)
	}
}